package com.indexingsystem.boss.utils;

import java.io.StringReader;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.TypeReference;

import com.indexingsystem.boss.common.BaseException;
import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;


/**
 * JSON工具类.
 * 
 * @author Administrator
 *
 */
public class JsonUtil {
	private ObjectMapper mapper;	

	public ObjectMapper getMapper() {
		return mapper;
	}

	public void setMapper(ObjectMapper mapper) {
		this.mapper = mapper;
	}
    
	@SuppressWarnings("deprecation")
	public JsonUtil(Inclusion inclusion) {
		mapper = new ObjectMapper();
		mapper.getSerializationConfig().setSerializationInclusion(inclusion);
		mapper.getDeserializationConfig()
				.set(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		setDateFormat(TimeUtil.theTimeFormat);
	}
	
	public JsonUtil(){
		super();
	}
	
	/**
	 * 创建输出全部属性
	 * 
	 * @return
	 */
	public static JsonUtil buildNormalBinder() {
		return new JsonUtil(Inclusion.ALWAYS);
	}

	

	/**
	 * 创建只输出非空属性的
	 * 
	 * @return
	 */
	public static JsonUtil buildNonNullBinder() {
		return new JsonUtil(Inclusion.NON_NULL);
	}

	/**
	 * 创建只输出初始值被改变的属性
	 * 
	 * @return
	 */
	public static JsonUtil buildNonDefaultBinder() {
		return new JsonUtil(Inclusion.NON_DEFAULT);
	}

	/**
	 * 把json字符串转成对象
	 * 
	 * @param json
	 * @param clazz
	 * @return
	 */
	public <T> T getJsonToObject(String json, Class<T> clazz) {
		T object = null;
		if (StringUtil.isNotBlank(json)) {
			try {
				object = getMapper().readValue(json, clazz);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return object;
	}

	/**
	 * 把JSON转成list
	 * 
	 * @param json
	 * @param typeReference
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "deprecation" })
	public Object getJsonToList(String json, TypeReference typeReference) {
		Object object = null;
		if (StringUtil.isNotBlank(json)) {
			try {
				object = getMapper().readValue(json, TypeFactory.fromTypeReference(typeReference));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return object;
	}

	
	private static Object getStrJson(String text){
		JSONObject jsStr = JSONObject.fromObject(text); 
		return jsStr;
	}
	
	/**
	 * 把JSON转成list
	 * 
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "deprecation" })
	public Object getJsonToList(String json, Class clazz) {
		Object object = null;
		if (StringUtil.isNotBlank(json)) {
			try {
				object = getMapper().readValue(json, TypeFactory.instance.constructParametricType(List.class, clazz));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return object;
	}

	/**
	 * 把JSON转成Map
	 * 
	 * @param json
	 * @param keyclazz
	 * @param valueclazz
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "deprecation" })
	public Object getJsonToMap(String json, Class keyclazz, Class valueclazz) {
		Object object = null;
		if (StringUtil.isNotBlank(json)) {
			try {
				object = getMapper().readValue(json,
						TypeFactory.instance.constructParametricType(Map.class, keyclazz, valueclazz));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return object;
	}

	/**
	 * 把json格式数据装成map
	 * 
	 * @param str
	 * @return
	 */
	public static Map<String, String> getJsonToMap(String str) {
		Map<String, String> map = new HashMap<String, String>();
		if (StringUtils.isNotBlank(str)) {
			String[] s = str.split(",");
			if (s.length > 0) {
				for (int i = 0; i < s.length; i++) {
					String con = s[i];
					int s1 = con.indexOf(":");
					if (s1 > 0) {
						map.put(con.substring(0, s1).trim().replace("\"", ""), con.substring(s1 + 1).replace("\"", ""));
					} else {
						map.put(con.trim().replace("\"", ""), "");
					}
				}
			}
		}
		return map;
	}

	/**
	 * 把map转成combo数据格式的json格式
	 * 
	 * @return String (json)
	 */
	public String getMapToJson(Map<String, String> map) {
		List<String[]> list = new ArrayList<String[]>();
		if (null != map && !map.isEmpty()) {
			for (String key : map.keySet()) {
				String[] strS = new String[2];
				strS[0] = key;
				strS[1] = map.get(key);
				list.add(strS);
			}
		}
		return jsonObject(list);
	}

	/**
	 * 把对象转成json格式
	 * 
	 * @param obj
	 *            需要转的对象
	 * @return String
	 */
	public String jsonObject(@SuppressWarnings("rawtypes") List list) {
		StringWriter sw = new StringWriter();
		JsonGenerator gen;
		try {
			gen = new JsonFactory().createJsonGenerator(sw);
			getMapper().writeValue(gen, list);
			gen.close();
		} catch (Exception e) {

		}
		return sw.toString();
	}

	/**
	 * 把JSON转成Object
	 * 
	 * @param json
	 * @param keyclazz
	 * @param valueclazz
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "deprecation" })
	public Object getJsonToObject(String json, Class objclazz, Class... pclazz) {
		Object object = null;
		if (StringUtil.isNotBlank(json)) {
			try {
				object = getMapper().readValue(json, TypeFactory.instance.constructParametricType(objclazz, pclazz));
			} catch (Exception e) {
			}
		}
		return object;
	}

	/**
	 * 把对象转成字符串
	 * 
	 * @param object
	 * @return
	 */
	public String toJson(Object object) {
		String json = null;
		try {
			json = getMapper().writeValueAsString(object);
		} catch (Exception e) {
		}
		return json;
	}

	/**
	 * 设置日期格式
	 * 
	 * @param pattern
	 */
	@SuppressWarnings("deprecation")
	public void setDateFormat(String pattern) {
		if (StringUtil.isNotBlank(pattern)) {
			DateFormat df = new SimpleDateFormat(pattern);
			getMapper().getSerializationConfig().setDateFormat(df);
			getMapper().getDeserializationConfig().setDateFormat(df);
		}
	}

	
	  /** 
     * JAVA对象转换成JSON字符串 
     *  
     * @param obj JAVA对象 
     * @return JSON字符串 
     * @throws MapperException 
     */  
    public static String obj2Json(Object obj) throws MapperException {  
        return obj2Json(obj, false);  
    }  
  
    /** 
     * JAVA数组对象转换成JSON字符串 
     *  
     * @param list JAVA数组对象 
     * @return JSON字符串 
     * @throws MapperException 
     */  
    public static String obj2Json(List<Class<?>> list) throws MapperException {  
        if (list == null || list.size() == 0) {  
            return "{}";  
        }  
        StringBuilder jsonString = new StringBuilder();  
        for (int i = 0; i < list.size(); i++) {  
            if (i != 0) {  
                jsonString.append(",");  
            }  
            Class<?> cla = list.get(i);  
            jsonString.append(obj2Json(cla, false));  
        }  
        return jsonString.toString();  
    }  
  
    /** 
     * JAVA集合对象转换成JSON字符串 
     *  
     * @param map JAVA集合对象 
     * @return JSON字符串 
     * @throws MapperException 
     */  
    public static String obj2Json(Map<String, Class<?>> map) throws MapperException {  
        if (map == null || map.size() == 0) {  
            return "{}";  
        }  
        StringBuilder jsonString = new StringBuilder();  
        Set<String> keySet = map.keySet();  
        boolean isFirst = true;  
        for (String key : keySet) {  
            if (isFirst) {  
                isFirst = false;  
            } else {  
                jsonString.append(",");  
            }  
            Class<?> cla = map.get(key);  
            jsonString.append(obj2Json(cla, false));  
        }  
        return jsonString.toString();  
    }        
 
  
    /** 
     * 重载objectToJsonStr方法 
     *  
     * @param obj 需要转换的JAVA对象 
     * @param format 是否格式化 
     * @return JSON字符串 
     * @throws MapperException 
     */  
    public static String obj2Json(Object obj, boolean format) throws MapperException {  
        JSONValue jsonValue = JSONMapper.toJSON(obj);  
        String jsonStr = jsonValue.render(format);  
        return jsonStr;  
    }  
  
    /** 
     * JSON字符串转换成JAVA对象 
     *  
     * @param jsonStr JSON字符串 
     * @param cla JAVA对象 
     * @return 转换后的对象 
     */  
    public static Object json2Obj(String jsonStr, Class<?> cla) throws MapperException {  
        Object obj = null;  
        try {  
            JSONParser parser = new JSONParser(new StringReader(jsonStr));  
            JSONValue jsonValue = parser.nextValue();  
            if (jsonValue instanceof com.sdicons.json.model.JSONArray) {  
                List<Object> list = new ArrayList<Object>();  
                JSONArray jsonArray = (JSONArray) jsonValue;  
                for (int i = 0; i < jsonArray.size(); i++) {  
                    JSONValue jsonObj = jsonArray.get(i);  
                    Object javaObj = JSONMapper.toJava(jsonObj, cla);  
                    list.add(javaObj);  
                }  
                obj = list;  
            } else if (jsonValue instanceof com.sdicons.json.model.JSONObject) {  
                obj = JSONMapper.toJava(jsonValue, cla);  
            } else {  
                obj = jsonValue;  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return obj;  
    }  	
    
    /**
     * Map转Json
     * 
     * @param maps 需要转换的map集合.
     * */
    public  static  String JsonStr(Map<String,String> maps) {
    	StringBuffer  str=new StringBuffer();
    	str.append("{");
    	Iterator it = maps.entrySet().iterator();  
		  while (it.hasNext()) {  
			   Map.Entry entry = (Map.Entry) it.next();  
			   Object key = entry.getKey();  
			   Object value = entry.getValue();  
			   str.append(key).append(":\"").append(value).append("\",");
		  }  
		String result=str.toString().substring(0, str.length()-1);  
		result=result+"}";
    	return  result.toString();
    	
    }
}